﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using KPIS.GERP.GBMS.APP_UI.Common;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.MODEL;
using Telerik.Web.UI;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class BGM_Project_KPI_New : System.Web.UI.Page
    {
        private StrategyKpiBLL straKpiBLL = new StrategyKpiBLL();
        private SystemTypeYearBLL sysTypeYearBLL = new SystemTypeYearBLL();
        private ComboBLL comboBLL = new ComboBLL();
        private CommandControl cmdFac = new CommandControl();
        private IStrategyPlanBLL bal = new StrategyPlanBLL();
        private bool isbind;
        private SsMng ssMng = new SsMng();
        private Main main = new Main();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BllType = Request.QueryString["type"];
                if (String.IsNullOrEmpty(BllType))
                {
                    throw new Exception("Fatal Error, Please specify project type");
                }

                ProjectID = Convert.ToString(Session["ProjectID"]);
                if (String.IsNullOrEmpty(ProjectID))
                {
                    throw new Exception("Fatal Error, Please specify project ID");
                }

                ProjectName = Convert.ToString(Session["ProjectName"]);

                loadKpiType();
                LoadData();
            }

        }

        private void LoadData()
        {
            {
                DataRow dr = sysTypeYearBLL.GetDataSystemTypeYear().Rows[0];
                MonthType = dr["month"].ToString();
            }

            {
                // If error, please insert
                //  INSERT INTO bgm_mas_year_type (bgm_year_type_name, day_start, month_start)
                //  VALUES ('ไตรมาสงบประมาณ', NULL, 4);
                //foreach (DataRow dr in sysTypeYearBLL.GetDataSystemTypeYear().Rows)
                //{
                //    if (dr["type"] as string == "ไตรมาสงบประมาณ")
                //        QuarterType = dr["month"].ToString();
                //}
                QuarterType = "1";
                if (String.IsNullOrEmpty(lblQuarterType.Text))
                {
                    throw new Exception("การตั้งค่าระบบ bgm_mas_year_type ยังไม่มีไตรมาสเริ่มต้น กรุณาใส่ข้อมูลลงไตรมาสงบประมาณลงในเทเบิ้ล");
                }
            }

            DataTable dt = ProjectBLL.GetDataProjectKPI(ProjectID);
            Grid.DataSource = dt;
            Grid.DataBind();
        }

        private void loadKpiType()
        {
            DataTable info = comboBLL.ListKpiType();
            ddlKpiType_t9.DataSource = info;
            ddlKpiType_t9.DataBind();
        }

        private void clear_t9()
        {
            txtName_t9.Text = "";
            txtDescr_t9.Text = "";
            txtUnit_t9.Text = "";
            txtWeight_t9.Text = "0";

            txtScore1_t9.Text = "0";
            txtScore2_t9.Text = "0";
            txtScore3_t9.Text = "0";
            txtScore4_t9.Text = "0";
            txtScore5_t9.Text = "0";

            txtTragetM1_t9.Text = "0";
            txtTragetM2_t9.Text = "0";
            txtTragetM3_t9.Text = "0";
            txtTragetM4_t9.Text = "0";
            txtTragetM5_t9.Text = "0";
            txtTragetM6_t9.Text = "0";
            txtTragetM7_t9.Text = "0";
            txtTragetM8_t9.Text = "0";
            txtTragetM9_t9.Text = "0";
            txtTragetM10_t9.Text = "0";
            txtTragetM11_t9.Text = "0";
            txtTragetM12_t9.Text = "0";

            txtTargetQ1.Text = "0";
            txtTargetQ2.Text = "0";
            txtTargetQ3.Text = "0";
            txtTargetQ4.Text = "0";

            txtTargetYear.Text = "0";

            txtMTEF1_t9.Text = "0";
            txtMTEF2_t9.Text = "0";
            txtMTEF3_t9.Text = "0";

            ddlTarket_t9.SelectedValue = "1";
            panelKpiMonthly.Visible = false;
            panelKpiQuarterly.Visible = true;
            panelKpiYearly.Visible = false;
        }

        private void MapLabel()
        {
            lblName_t9.Text = txtName_t9.Text;
            lblDescr_t9.Text = txtDescr_t9.Text;
            lblUnit_t9.Text = txtUnit_t9.Text;
            lblWeight_t9.Text = txtWeight_t9.Text;

            lblScore1_t9.Text = txtScore1_t9.Text;
            lblScore2_t9.Text = txtScore2_t9.Text;
            lblScore3_t9.Text = txtScore3_t9.Text;
            lblScore4_t9.Text = txtScore4_t9.Text;
            lblScore5_t9.Text = txtScore5_t9.Text;

            lblTragetM1_t9.Text = txtTragetM1_t9.Text;
            lblTragetM2_t9.Text = txtTragetM2_t9.Text;
            lblTragetM3_t9.Text = txtTragetM3_t9.Text;
            lblTragetM4_t9.Text = txtTragetM4_t9.Text;
            lblTragetM5_t9.Text = txtTragetM5_t9.Text;
            lblTragetM6_t9.Text = txtTragetM6_t9.Text;
            lblTragetM7_t9.Text = txtTragetM7_t9.Text;
            lblTragetM8_t9.Text = txtTragetM8_t9.Text;
            lblTragetM9_t9.Text = txtTragetM9_t9.Text;
            lblTragetM10_t9.Text = txtTragetM10_t9.Text;
            lblTragetM11_t9.Text = txtTragetM11_t9.Text;
            lblTragetM12_t9.Text = txtTragetM12_t9.Text;

            lblMTEF1_t9.Text = txtMTEF1_t9.Text;
            lblMTEF2_t9.Text = txtMTEF2_t9.Text;
            lblMTEF3_t9.Text = txtMTEF3_t9.Text;
        }

        private void bindTab9_forEdit(string seq)
        {
            lblSeq_t9.Text = seq;

            DataRow dr = ProjectBLL.GetDataProjectKPIBySequence(seq).Rows[0];

            txtName_t9.Text = dr["bgm_prj_kpi_name"].ToString();
            txtDescr_t9.Text = dr["bgm_prj_kpi_descr"].ToString();
            txtUnit_t9.Text = dr["unit"].ToString();
            txtWeight_t9.Text = dr["bgm_prj_kpi_weight"].ToString();
            txtScore1_t9.Text = dr["score_1"].ToString();
            txtScore2_t9.Text = dr["score_2"].ToString();
            txtScore3_t9.Text = dr["score_3"].ToString();
            txtScore4_t9.Text = dr["score_4"].ToString();
            txtScore5_t9.Text = dr["score_5"].ToString();
            SetMonthDataRow(dr);
            txtMTEF1_t9.Text = dr["mtef_1"].ToString();
            txtMTEF2_t9.Text = dr["mtef_2"].ToString();
            txtMTEF3_t9.Text = dr["mtef_3"].ToString();
            ddlKpiType_t9.SelectedValue = dr["bgm_kpi_type_seq"].ToString();
            ddlTarket_t9.SelectedValue = dr["target_type"].ToString();
        }


        private void OnInsert(object sender, EventArgs e)
        {
            txtMTEF1_t9.Text = txtMTEF1_t9.Text != "" ? txtMTEF1_t9.Text : "0";
            txtMTEF2_t9.Text = txtMTEF2_t9.Text != "" ? txtMTEF2_t9.Text : "0";
            txtMTEF3_t9.Text = txtMTEF3_t9.Text != "" ? txtMTEF3_t9.Text : "0";

            try
            {
                string m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12;
                GetMonthUi(out m1, out m2, out m3, out m4, out m5, out m6,
                              out m7, out m8, out m9, out m10, out m11, out m12);
                ProjectBLL.InsertProjectKPI(txtName_t9.Text, txtDescr_t9.Text, txtUnit_t9.Text, txtWeight_t9.Text, ProjectID, ddlKpiType_t9.SelectedValue
                    , txtScore1_t9.Text, txtScore2_t9.Text, txtScore3_t9.Text, txtScore4_t9.Text, txtScore5_t9.Text , ddlTarket_t9.SelectedValue
                    , m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12
                    , txtMTEF1_t9.Text, txtMTEF2_t9.Text, txtMTEF3_t9.Text, ssMng.EmpSeq);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('บันทึกเสร็จเรียบร้อย');", true);
            }
            catch
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('เกิดข้อผิดพลาดในการบันทึก');", true);
            }

            LoadData();
            panelList.Visible = false; 
        }

        private void OnUpdate(object sender, EventArgs e)
        {
            txtMTEF1_t9.Text = txtMTEF1_t9.Text != "" ? txtMTEF1_t9.Text : "0";
            txtMTEF2_t9.Text = txtMTEF2_t9.Text != "" ? txtMTEF2_t9.Text : "0";
            txtMTEF3_t9.Text = txtMTEF3_t9.Text != "" ? txtMTEF3_t9.Text : "0";
            try
            {
                string m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12;
                GetMonthUi(out m1, out m2, out m3, out m4, out m5, out m6,
                              out m7, out m8, out m9, out m10, out m11, out m12);
                ProjectBLL.UpdateProjectKPI(lblSeq_t9.Text, txtName_t9.Text, txtDescr_t9.Text, txtUnit_t9.Text, txtWeight_t9.Text, ddlKpiType_t9.SelectedValue
                     , txtScore1_t9.Text, txtScore2_t9.Text, txtScore3_t9.Text, txtScore4_t9.Text, txtScore5_t9.Text, ddlTarket_t9.SelectedValue
                     , m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12
                     , txtMTEF1_t9.Text, txtMTEF2_t9.Text, txtMTEF3_t9.Text, ssMng.EmpSeq);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('บันทึกเสร็จเรียบร้อย');", true);
            }
            catch
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('เกิดข้อผิดพลาดในการบันทึก');", true);
            }

            LoadData(); 
            panelList.Visible = false;
            MapLabel();



        }

        private void OnDelete(object sender, EventArgs e)
        {
            int nRowSelected = 0;
            foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
            {
                ProjectBLL.DeleteProjectKPI(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Sequence"].ToString());
                nRowSelected++;
            }
            panelList.Visible = false;
            LoadData();
            RefreshGrid();
        }

        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "TargetInsertClick")
            {
                panelList.Visible = true;
                clear_t9();
                Save_AddNew.Visible = true;
                Save_Edit.Visible = false;
            } else if (e.CommandName == "TargetClick")
            {
                string key_grid1 = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Sequence"].ToString();
                bindTab9_forEdit(key_grid1);
                cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
                panelList.Visible = true;
                panelGrid.Visible = false;
                return;
            }            
            else if (e.CommandName == RadGrid.ExpandCollapseCommandName)
            {
                string key_grid1 = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Sequence"].ToString();
                DataTable dt = ProjectBLL.GetDataProjectKPIBySequence(key_grid1);

                RadGrid grdIn_t9 = (RadGrid)((GridDataItem)e.Item).ChildItem.FindControl("GridIn_t9");
                grdIn_t9.DataSource = dt;
                grdIn_t9.DataBind();
                return;
            } else if (e.CommandName == "Delete")
            {
                int nRowSelected = 0;
                foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
                {
                    ProjectBLL.DeleteProjectKPI(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Sequence"].ToString());
                    nRowSelected++;
                }
                panelList.Visible = false;
            } 
            LoadData();
            RefreshGrid(); 
        }




        protected void Grid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (!isbind)
            {
                RadGrid grid = (RadGrid)sender;
                var ds = GetHeaderText();
                foreach (GridColumn c in grid.MasterTableView.Columns)
                {
                    var uiMap = ds.FirstOrDefault(o => o.HeaderKey == c.UniqueName);
                    if (uiMap != null)
                    {
                        c.HeaderText = uiMap.Value;
                        ((Literal)panelList.FindControl(uiMap.LabelKey)).Text = String.Format("{0}:", uiMap.Value);
                    }
                }
                isbind = true;
            }
        }

        //#####################  Command Control In page  --- Event
        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            //cmdFac.GridCommand(panelList, panelGrid, panelCommand);
            cmdFac.SetPanelCommand(panelCommand, "Grid");
            loadKpiType();
            LoadData();
            Grid.Visible = true;
            panelGrid.Visible = true;
            panelList.Visible = false;
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            //cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
            cmdFac.SetPanelCommand(panelCommand, "AddNew");
            panelGrid.Visible = false;
            panelList.Visible = true; 
            cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
            clear_t9();
            //cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
        }

        protected void Edit_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList, panelGrid, panelCommand);
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList, panelGrid, panelCommand);
            loadKpiType();
            LoadData();
            Grid.Visible = true;
            panelGrid.Visible = true;
            panelList.Visible = false;
        }

        protected void Save_AddNew_Click(object sender, EventArgs e)
        {
            MapLabel();
            OnInsertCommand(e);
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
            
        }

        protected void Save_Edit_Click(object sender, EventArgs e)
        {
            OnUpdateCommand(e);
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            OnDeleteCommand(e);
        }

        public void MapControl()
        {
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
        }

        public void RefreshGrid()
        {
            cmdFac.GridCommand(panelList, panelGrid, panelCommand);
        }

        protected void OnInsertCommand(EventArgs e)
        {
            OnInsert(null, null);
        }

        protected void OnUpdateCommand(EventArgs e)
        {
            OnUpdate(null, null);
        }

        protected void OnDeleteCommand(EventArgs e)
        {
            OnDelete(null, null);
        }
        #region MiscMethod
        private List<UiMap> GetHeaderText()
        {
            List<UiMap> result = new List<UiMap>();

            int monType = int.Parse(lblMonthType.Text) - 1;

            for (int i = 0; i < StrMonth.Length; i++, monType++)
            {
                if (monType >= StrMonth.Length)
                    monType = 0;
                result.Add(new UiMap { HeaderKey = "target_m" + (i + 1), Value = StrMonth[monType], LabelKey = "lblMonth" + (i + 1) });
            }

            int quarType = int.Parse(lblQuarterType.Text) - 1;

            for (int i = 0; i < StrQuarter.Length; i++, quarType++)
            {
                if (quarType >= StrQuarter.Length)
                    quarType = 0;
                result.Add(new UiMap { HeaderKey = "target_q" + (i + 1), Value = StrQuarter[quarType], LabelKey = "lblQuarter" + (i + 1) });
            }

            result.Add(new UiMap { HeaderKey = "target_year", Value = StrYear, LabelKey = "lblYearCaption" });

            return result;
        }

        private void SetMonthDataRow(DataRow dr)
        {
            txtTragetM1_t9.Text = main.MakeZero(dr["target_m1"]);
            txtTragetM2_t9.Text = main.MakeZero(dr["target_m2"]);
            txtTragetM3_t9.Text = main.MakeZero(dr["target_m3"]);
            txtTragetM4_t9.Text = main.MakeZero(dr["target_m4"]);
            txtTragetM5_t9.Text = main.MakeZero(dr["target_m5"]);
            txtTragetM6_t9.Text = main.MakeZero(dr["target_m6"]);
            txtTragetM7_t9.Text = main.MakeZero(dr["target_m7"]);
            txtTragetM8_t9.Text = main.MakeZero(dr["target_m8"]);
            txtTragetM9_t9.Text = main.MakeZero(dr["target_m9"]);
            txtTragetM10_t9.Text = main.MakeZero(dr["target_m10"]);
            txtTragetM11_t9.Text = main.MakeZero(dr["target_m11"]);
            txtTragetM12_t9.Text = main.MakeZero(dr["target_m12"]);

            txtTargetQ1.Text = main.MakeZero(dr["target_q1"]);
            txtTargetQ2.Text = main.MakeZero(dr["target_q2"]);
            txtTargetQ3.Text = main.MakeZero(dr["target_q3"]);
            txtTargetQ4.Text = main.MakeZero(dr["target_q4"]);

            txtTargetYear.Text = main.MakeZero(dr["target_year"]);
        }

        private void GetMonthUi(out string m1, out string m2, out string m3, out string m4, out string m5, out string m6
            , out string m7, out string m8, out string m9, out string m10, out string m11, out string m12)
        {
            m1 = null; m2 = null; m3 = null; m4 = null; m5 = null; m6 = null;
            m7 = null; m8 = null; m9 = null; m10 = null; m11 = null; m12 = null;
            switch (ddlTarket_t9.SelectedValue)
            {
                case "2": // เป้าหมายรวมรายเดือน
                    m1 = main.MakeZero(txtTragetM1_t9.Text);
                    m2 = main.MakeZero(txtTragetM2_t9.Text);
                    m3 = main.MakeZero(txtTragetM3_t9.Text);
                    m4 = main.MakeZero(txtTragetM4_t9.Text);
                    m5 = main.MakeZero(txtTragetM5_t9.Text);
                    m6 = main.MakeZero(txtTragetM6_t9.Text);
                    m7 = main.MakeZero(txtTragetM7_t9.Text);
                    m8 = main.MakeZero(txtTragetM8_t9.Text);
                    m9 = main.MakeZero(txtTragetM9_t9.Text);
                    m10 = main.MakeZero(txtTragetM10_t9.Text);
                    m11 = main.MakeZero(txtTragetM11_t9.Text);
                    m12 = main.MakeZero(txtTragetM12_t9.Text);
                    break;
                case "1": // เป้าหมายรวมรายไตรมาส
                    m1 = "0";
                    m2 = "0";
                    m3 = main.MakeZero(txtTargetQ1.Text);
                    m4 = "0";
                    m5 = "0";
                    m6 = main.MakeZero(txtTargetQ2.Text);
                    m7 = "0";
                    m8 = "0";
                    m9 = main.MakeZero(txtTargetQ3.Text);
                    m10 = "0";
                    m11 = "0";
                    m12 = main.MakeZero(txtTargetQ4.Text);
                    break;
                case "0": // เป้าหมายรวมรายปี
                    m1 = "0";
                    m2 = "0";
                    m3 = "0";
                    m4 = "0";
                    m5 = "0";
                    m6 = "0";
                    m7 = "0";
                    m8 = "0";
                    m9 = "0";
                    m10 = "0";
                    m11 = "0";
                    m12 = main.MakeZero(txtTargetYear.Text);
                    break;
            }
        }

        private void SetPanelKpiVisible()
        {
            switch (ddlTarket_t9.SelectedValue)
            {
                case "2": // เป้าหมายรวมรายเดือน
                    panelKpiMonthly.Visible = true;
                    panelKpiQuarterly.Visible = false;
                    panelKpiYearly.Visible = false;
                    break;
                case "1": // เป้าหมายรวมรายไตรมาส
                    panelKpiMonthly.Visible = false;
                    panelKpiQuarterly.Visible = true;
                    panelKpiYearly.Visible = false;
                    break;
                case "0": // เป้าหมายรวมรายปี
                    panelKpiMonthly.Visible = false;
                    panelKpiQuarterly.Visible = false;
                    panelKpiYearly.Visible = true;
                    break;
            }
        }

        #endregion

        #region Properties

        private class UiMap
        {
            public string HeaderKey { get; set; }
            public string LabelKey { get; set; }
            public string Value { get; set; }
        }

        private string[] StrMonth
        {
            get { return (GetLocalResourceObject("MonthString") as string).Split(',').ToArray(); }
        }

        private string[] StrQuarter
        {
            get { return (GetLocalResourceObject("QuarterString") as string).Split(',').ToArray(); }
        }

        private string StrYear
        {
            get { return (GetLocalResourceObject("YearlyString") as string); }
        }

        private IProject ProjectBLL
        {
            get
            {
                return Project_Factory.GetProjectFactory(BllType);
            }
        }

        private string BllType
        {
            get { return bllType.Text; }
            set
            {
                bllType.Text = value;
            }
        }
        private string ProjectID
        {
            get { return lblProjectID.Text; }
            set { lblProjectID.Text = value; }
        }
        private string ProjectName
        {
            get { return Page.Title; }
            set
            {
                Page.Title = value;
                lblProjectName.Text = value;
            }
        }
        private string MonthType
        {
            get { return lblMonthType.Text; }
            set { lblMonthType.Text = value; }
        }
        private string QuarterType
        {
            get { return lblQuarterType.Text; }
            set { lblQuarterType.Text = value; }
        }
        #endregion

        protected void ddlTarket_t9_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        { 
            switch (e.Value)
            {
                case "2": // เป้าหมายรวมรายเดือน
                    panelKpiMonthly.Visible = true;
                    panelKpiQuarterly.Visible = false;
                    panelKpiYearly.Visible = false;
                    break;
                case "1": // เป้าหมายรวมรายไตรมาส
                    panelKpiMonthly.Visible = false;
                    panelKpiQuarterly.Visible = true;
                    panelKpiYearly.Visible = false;
                    break;
                case "0": // เป้าหมายรวมรายปี
                    panelKpiMonthly.Visible = false;
                    panelKpiQuarterly.Visible = false;
                    panelKpiYearly.Visible = true;
                    break;
                default:
                    break;
            }
        } 
    }
}
